package com.sleep.psy.external_server.annotation;


import com.sleep.psy.external_server.annotation.entity.UserInfoRes;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserInfoRes.class)
                && parameter.hasParameterAnnotation(com.sleep.psy.external_server.annotation.CurrentUser.class);
    }

    @Nullable
    @Override
    public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
        UserInfoRes userInfoRes = (UserInfoRes) webRequest.getAttribute("currentUser", RequestAttributes.SCOPE_REQUEST);
        if (userInfoRes != null) {
            return userInfoRes;
        }
        throw new MissingServletRequestPartException("currentUser");
    }
}
